<template>
  <div>
    <el-upload :class="{disabled:disabled}" :file-list="fileList" action="#" list-type="picture-card" :on-remove="onRemove" :on-change="onChange" :on-preview="onPreview" :before-upload="beforeUpload" :http-request="httpRequest">
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览图片" :visible.sync="dialogShow">
      <img style="width:100%" :src="imgUrl" alt="">
    </el-dialog>
    <el-progress v-if="percentageShow" style="width: 180px" :percentage="percentageNumber" />
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
var cos = new Cos({
  SecretId: 'AKIDfBVbSmuoVxA9tNdYGjOq9F7kBNK2awDJ', // 身份识别 ID
  SecretKey: 'veARTHrHckgPvDI9nCMK4au2xdHk15uX' // 身份密钥
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      percentageShow: false,
      percentageNumber: 0,
      imgUrl: '',
      dialogShow: false,
      fileList: [],
      currentUid: ''
    }
  },
  computed: {
    disabled() {
      return this.fileList.length === 1
    }
  },
  methods: {
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    onChange(file, fileList) {
      console.log(JSON.stringify(file))
      this.fileList = fileList
    },
    onPreview(file, fileList) {
      console.log(file)
      this.dialogShow = true
      this.imgUrl = file.url
    },
    beforeUpload(file) {
      // 1.格式校验
      const typeArr = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg']
      if (!typeArr.includes(file.type)) {
        this.$message.warning('格式不正确')
        return false
      }
      // 体积校验
      if (file.size >= 1024 * 1024 * 2) {
        this.$message.warning('体积不允许超过2M')
        return false
      }
      this.currentUid = file.uid
      this.percentageShow = true
      return true
    },
    httpRequest(data) {
      console.log(data.file)
      cos.putObject({
        Bucket: 'klara-1316282051', // 存储桶
        Region: 'ap-nanjing', // 地域
        Key: data.file.name, // 文件名
        Body: data.file, // 要上传的文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentageNumber = progressData.percent * 100
        }
      },
      (err, data) => {
        // 替换成箭头函数才可以正常使用
        if (err) return this.$message.warning('上传失败')
        console.log(err || data)
        this.fileList.map((item) => {
          if (item.uid === this.currentUid) {
            item.url = 'http://' + data.Location
            item.upload = true
          }
          this.$message.success('上传成功')
        })
        setTimeout(() => {
          this.percentageShow = false
          this.percentageNumber = 0
        }, 1000)
      }
      )
    }
  }
}

</script>

<style scoped lang="scss">
 .disabled{
  ::v-deep .el-upload--picture-card{
    display: none;
  }
}
</style>
